package com.ywl.study.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
public class ChainTrasactionConfig {

    @Resource
    DataSource mysqlUserDataSource;

    @Resource
    DataSource mysqlOrderDataSource;

    @Resource
    DataSource oracleUserDataSource;

    @Resource
    DataSource oracleOrderDataSource;

    /*创建链式事务管理器*/
    @Bean
    public PlatformTransactionManager transactionManager() {
        /*spirng 会从容器中获取userDataSource和orderDataSource 注入到DataSourceTransactionManager构造函数中*/
        /*如果是userTm.setDataSource(xxx) 的话，则不是从容器中获取datasource*/
        DataSourceTransactionManager mysqlUserTm = new DataSourceTransactionManager(mysqlUserDataSource);
        DataSourceTransactionManager mysqlOrderTm = new DataSourceTransactionManager(mysqlOrderDataSource);
        DataSourceTransactionManager oracleUserTm = new DataSourceTransactionManager(oracleUserDataSource);
        DataSourceTransactionManager oracleOrderTm = new DataSourceTransactionManager(oracleOrderDataSource);
        ChainedTransactionManager chainManager = new ChainedTransactionManager(mysqlUserTm, mysqlOrderTm,oracleUserTm,oracleOrderTm);
        return chainManager;
    }
}
